﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.BusinessLogic.Utils;
using NopSolutions.NopCommerce.Common.Utils;

namespace NopSolutions.NopCommerce.Web.Templates.Products
{
    public partial class OneVariant : BaseNopFrontendUserControl
    {
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            if (!IsPostBack) {
                BindData();
            }
        }

        protected void BindData() {
            var product = this.ProductService.GetProductById(this.ProductId);
            if (product == null || product.ProductVariants.Count == 0) {
                Response.Redirect(CommonHelper.GetStoreLocation());
            }
            //ctrlProductRating.Visible = product.AllowCustomerRatings;
            BindProductVariantInfo(ProductVariant);
            BindProductInfo(product);
        }

        protected void BindProductInfo(Product product) {
            lProductName.Text = Server.HtmlEncode(product.LocalizedName);
            lShortDescription.Text = product.LocalizedShortDescription;
            lFullDescription.Text = product.LocalizedFullDescription;
            //manufacturers
            List<Manufacturer> manufacturers = new List<Manufacturer>();
            foreach (var pm in product.ProductManufacturers) {
                var manufacturer = pm.Manufacturer;
                if (manufacturer != null)
                    manufacturers.Add(manufacturer);
            }
            if (manufacturers.Count > 0) {
                if (manufacturers.Count == 1) {
                    lManufacturersTitle.Text = GetLocaleResourceString("Products.Manufacturer");
                } else {
                    lManufacturersTitle.Text = GetLocaleResourceString("Products.Manufacturers");
                }
                rptrManufacturers.DataSource = manufacturers;
                rptrManufacturers.DataBind();
            } else {
                phManufacturers.Visible = false;
            }

            //pictures
            var pictures = this.PictureService.GetPicturesByProductId(product.ProductId);
            if (pictures.Count > 1) {
                defaultImage.ImageUrl = this.PictureService.GetPictureUrl(pictures[0], this.SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 300));
                defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                rptProductPictures.DataSource = pictures;
                rptProductPictures.DataBind();
            } else if (pictures.Count == 1) {
                defaultImage.ImageUrl = this.PictureService.GetPictureUrl(pictures[0], this.SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 300));
                defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                rptProductPictures.Visible = false;
            } else {
                defaultImage.ImageUrl = this.PictureService.GetDefaultPictureUrl(this.SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 300));
                defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                rptProductPictures.Visible = false;
            }
            if (this.SettingManager.GetSettingValueBoolean("Media.Product.DefaultPictureZoomEnabled", false)) {
                var picture = product.DefaultPicture;
                if (picture != null) {
                    lnkMainLightbox.Attributes["href"] = this.PictureService.GetPictureUrl(picture);
                    lnkMainLightbox.Attributes["rel"] = "lightbox";
                }
            }
        }

        protected void BindProductVariantInfo(ProductVariant productVariant) {
            btnAddToWishlist.Visible = this.SettingManager.GetSettingValueBoolean("Common.EnableWishlist");
            litDescription.Text = productVariant.LocalizedDescription;

            //sku
            if (this.SettingManager.GetSettingValueBoolean("Display.Products.ShowSKU") &&
                !String.IsNullOrEmpty(productVariant.SKU)) {
                phSKU.Visible = true;
                lSKU.Text = Server.HtmlEncode(productVariant.SKU);
            } else {
                phSKU.Visible = false;
            }

            //manufacturer part number
            if (this.SettingManager.GetSettingValueBoolean("Display.Products.ShowManufacturerPartNumber") &&
                !String.IsNullOrEmpty(productVariant.ManufacturerPartNumber)) {
                phManufacturerPartNumber.Visible = true;
                lManufacturerPartNumber.Text = Server.HtmlEncode(productVariant.ManufacturerPartNumber);
            } else {
                phManufacturerPartNumber.Visible = false;
            }

            ctrlTierPrices.ProductVariantId = productVariant.ProductVariantId;
            ctrlProductAttributes.ProductVariantId = productVariant.ProductVariantId;
            ctrlGiftCardAttributes.ProductVariantId = productVariant.ProductVariantId;
            ctrlProductPrice.ProductVariantId = productVariant.ProductVariantId;

            //stock
            string stockMessage = productVariant.FormatStockMessage();
            if (!String.IsNullOrEmpty(stockMessage)) {
                if (productVariant.StockQuantity > 0) {
                    pnlStockAvailablity.CssClass = "alert-box success";
                } else {
                    pnlStockAvailablity.CssClass = "alert-box error";
                }
                lblStockAvailablity.Text = stockMessage;
            } else {
                pnlStockAvailablity.Visible = false;
            }

            //price entered by a customer
            if (productVariant.CustomerEntersPrice) {
                decimal minimumCustomerEnteredPrice = this.CurrencyService.ConvertCurrency(productVariant.MinimumCustomerEnteredPrice, this.CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                decimal maximumCustomerEnteredPrice = this.CurrencyService.ConvertCurrency(productVariant.MaximumCustomerEnteredPrice, this.CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                txtCustomerEnteredPrice.Visible = true;
                txtCustomerEnteredPrice.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);
                txtCustomerEnteredPrice.Value = minimumCustomerEnteredPrice;
                txtCustomerEnteredPrice.MinimumValue = minimumCustomerEnteredPrice.ToString();
                txtCustomerEnteredPrice.MaximumValue = maximumCustomerEnteredPrice.ToString();
                txtCustomerEnteredPrice.RangeErrorMessage = string.Format(GetLocaleResourceString("Products.CustomerEnteredPrice.Range"),
                    PriceHelper.FormatPrice(minimumCustomerEnteredPrice, false, false),
                        PriceHelper.FormatPrice(maximumCustomerEnteredPrice, false, false));
            } else {
                txtCustomerEnteredPrice.Visible = false;
            }

            //buttons
            if (!productVariant.DisableBuyButton) {
                txtQuantity.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);
                btnAddToCart.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);
                btnAddToWishlist.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);

                txtQuantity.Value = productVariant.OrderMinimumQuantity;
            } else {
                txtQuantity.Visible = false;
                btnAddToCart.Visible = false;
                btnAddToWishlist.Visible = false;
            }

            //samle downlaods
            if (pnlDownloadSample != null && hlDownloadSample != null) {
                if (productVariant.IsDownload && productVariant.HasSampleDownload) {
                    pnlDownloadSample.Visible = true;
                    hlDownloadSample.NavigateUrl = this.DownloadService.GetSampleDownloadUrl(productVariant);
                } else {
                    pnlDownloadSample.Visible = false;
                }
            }

            //final check - hide prices for non-registered customers
            if (!this.SettingManager.GetSettingValueBoolean("Common.HidePricesForNonRegistered") ||
                    (NopContext.Current.User != null &&
                    !NopContext.Current.User.IsGuest)) {
                //
            } else {
                txtCustomerEnteredPrice.Visible = false;
                txtQuantity.Visible = false;
                btnAddToCart.Visible = false;
                btnAddToWishlist.Visible = false;
            }
        }

        public int ProductId {
            get {
                return CommonHelper.RouteStringInt("productId");
            }
        }

        public ProductVariant ProductVariant {
            get {
                Product product = this.ProductService.GetProductById(this.ProductId);
                if (product == null && product.ProductVariants.Count == 0) {
                    return null;
                }
                return product.ProductVariants[0];
            }
        }

        protected void OnCommand(object source, CommandEventArgs e) {
            var pv = ProductVariant;
            if (pv == null) {
                return;
            }
            ctrlProductAttributes.ProductVariantId = ProductVariant.ProductVariantId;
            string attributes = ctrlProductAttributes.SelectedAttributes;
            decimal customerEnteredPrice = txtCustomerEnteredPrice.Value;
            decimal customerEnteredPriceConverted = this.CurrencyService.ConvertCurrency(customerEnteredPrice, NopContext.Current.WorkingCurrency, this.CurrencyService.PrimaryStoreCurrency);
            int quantity = txtQuantity.Value; //int.Parse(Request.Form[txtQuantity.UniqueID]); //txtQuantity.Value;

            //gift cards
            if (pv.IsGiftCard) {
                string recipientName = ctrlGiftCardAttributes.RecipientName;
                string recipientEmail = ctrlGiftCardAttributes.RecipientEmail;
                string senderName = ctrlGiftCardAttributes.SenderName;
                string senderEmail = ctrlGiftCardAttributes.SenderEmail;
                string giftCardMessage = ctrlGiftCardAttributes.GiftCardMessage;

                attributes = ProductAttributeHelper.AddGiftCardAttribute(attributes, recipientName, recipientEmail, senderName, senderEmail, giftCardMessage);
            }

            try {
                if (e.CommandName == "AddToCart") {
                    var addToCartWarnings = this.ShoppingCartService.AddToCart(
                        ShoppingCartTypeEnum.ShoppingCart,
                        pv.ProductVariantId,
                        attributes,
                        customerEnteredPriceConverted,
                        quantity);
                    if (addToCartWarnings.Count == 0) {
                        if (this.SettingManager.GetSettingValueBoolean("Display.Products.DisplayCartAfterAddingProduct")) {
                            //redirect to shopping cart page
                            Response.Redirect(SEOHelper.GetShoppingCartUrl());
                        } else {
                            //display notification message
                            this.DisplayAlertMessage(GetLocaleResourceString("Products.ProductHasBeenAddedToTheCart"));
                        }
                    } else {
                        var addToCartWarningsSb = new StringBuilder();
                        //addToCartWarningsSb.Append("<p>" + GetLocaleResourceString("Products.RequiredAttributes") + "</p>");
                        addToCartWarningsSb.Append("<ul>");
                        for (int i = 0; i < addToCartWarnings.Count; i++) {
                            addToCartWarningsSb.Append("<li>" + Server.HtmlEncode(addToCartWarnings[i]) + "</li>");
                        }
                        addToCartWarningsSb.Append("</ul>");
                        string errorFull = addToCartWarningsSb.ToString();
                        pnlAlert.Visible = true;
                        lblError.Text = errorFull;
                        if (this.SettingManager.GetSettingValueBoolean("Common.ShowAlertForProductAttributes")) {
                            this.DisplayAlertMessage(errorFull);
                        }
                    }
                }

                if (e.CommandName == "AddToWishlist") {
                    var addToCartWarnings = this.ShoppingCartService.AddToCart(
                        ShoppingCartTypeEnum.Wishlist,
                        pv.ProductVariantId,
                        attributes,
                        customerEnteredPriceConverted,
                        quantity);
                    if (addToCartWarnings.Count == 0) {
                        Response.Redirect(SEOHelper.GetWishlistUrl());
                    } else {
                        var addToCartWarningsSb = new StringBuilder();
                        //addToCartWarningsSb.Append("<p>" + GetLocaleResourceString("Products.RequiredAttributes") + "</p>");
                        addToCartWarningsSb.Append("<ul>");
                        for (int i = 0; i < addToCartWarnings.Count; i++) {
                            addToCartWarningsSb.Append("<li>" + Server.HtmlEncode(addToCartWarnings[i]) + "</li>");
                        }
                        addToCartWarningsSb.Append("</ul>");
                        string errorFull = addToCartWarningsSb.ToString();
                        pnlAlert.Visible = true;
                        lblError.Text = errorFull;
                        if (this.SettingManager.GetSettingValueBoolean("Common.ShowAlertForProductAttributes")) {
                            this.DisplayAlertMessage(errorFull);
                        }
                    }
                }
            } catch (Exception exc) {
                this.LogService.InsertLog(LogTypeEnum.CustomerError, exc.Message, exc);
                pnlAlert.Visible = true;
                lblError.Text = Server.HtmlEncode(exc.Message);
            }
        }
    }
}